package com.dddframework.core.contract;

import cn.hutool.core.collection.CollUtil;
import com.dddframework.core.context.BaseContext;

import java.io.Serializable;
import java.util.List;

/**
 * 基础模型，支持增删改的充血模型
 *
 * @author Jensen
 * @公众号 架构师修行录
 */
public class Model implements Serializable {

    public static <T extends BaseRepository<D, Q>, D extends Model, Q extends Query> T getRepository(Class<?> clazz) {
        return BaseContext.get(clazz);
    }

    public boolean save() {
        return getRepository(this.getClass()).save(this);
    }

    public boolean update() {
        return getRepository(this.getClass()).update(this);
    }

    public boolean update(Query query) {
        return getRepository(query.getClass()).update(this, query);
    }

    public boolean updateByKey() {
        return getRepository(this.getClass()).updateByKey(this);
    }

    public <Q extends Query> void fill(Q query) {
        getRepository(this.getClass()).fill(query, this);
    }

    public static boolean save(List<? extends Model> models) {
        if (CollUtil.isEmpty(models)) return false;
        return getRepository(models.get(0).getClass()).save(models);
    }

    public static boolean update(List<? extends Model> models) {
        if (CollUtil.isEmpty(models)) return false;
        return getRepository(models.get(0).getClass()).update(models);
    }

    public static boolean updateByKey(List<? extends Model> models) {
        if (CollUtil.isEmpty(models)) return false;
        return getRepository(models.get(0).getClass()).updateByKey(models);
    }

    public static boolean delete(Query query) {
        return getRepository(query.getClass()).delete(query);
    }

}